package androidgame.framework.gl;

// Provides bitmap font functionality. drawText works the same as drawSprite in SpriteBatcher. x,y coords are the center of the
// first letter. to-do: Add easier drawing functionality such as drawing from bottom left corner or center of entire string.
// Completed: Use drawTextCenter for drawing from the center of the string and drawTextCorner for drawing from the lower left
// corner of the string.
// @author dicarlo2

public class Font {
	public final Texture texture;
	public final int glyphWidth;
	public final int glyphHeight;
	public final TextureRegion[] glyphs = new TextureRegion[96];

	public Font(Texture texture, int offsetX, int offsetY, int glyphsPerRow,
			int glyphWidth, int glyphHeight) {
		this.texture = texture;
		this.glyphWidth = glyphWidth;
		this.glyphHeight = glyphHeight;
		int x = offsetX;
		int y = offsetY;
		for (int i = 0; i < 96; i++) {
			glyphs[i] = new TextureRegion(texture, x, y, glyphWidth,
					glyphHeight);
			x += glyphWidth;
			if (x == offsetX + glyphsPerRow * glyphWidth) {
				x = offsetX;
				y += glyphHeight;
			}
		}
	}

	public void drawText(SpriteBatcher batcher, String text, float x, float y) {
		int len = text.length();
		for (int i = 0; i < len; i++) {
			int c = text.charAt(i) - ' ';
			if (c < 0 || c > glyphs.length - 1)
				continue;

			TextureRegion glyph = glyphs[c];
			batcher.drawSprite(x, y, glyphWidth, glyphHeight, glyph);
			x += glyphWidth;
		}
	}

	public void drawText(SpriteBatcher batcher, String text, float x, float y,
			float glyphWidth, float glyphHeight) {
		int len = text.length();
		for (int i = 0; i < len; i++) {
			int c = text.charAt(i) - ' ';
			if (c < 0 || c > glyphs.length - 1)
				continue;

			TextureRegion glyph = glyphs[c];
			batcher.drawSprite(x, y, glyphWidth, glyphHeight, glyph);
			x += glyphWidth;
		}
	}

	// Wrapper method. Draws text from center of string.
	public void drawTextCenter(SpriteBatcher batcher, String text, float x,
			float y) {
		int len = text.length();
		x = x - ((len * glyphWidth) / 2) + glyphWidth / 2;
		drawText(batcher, text, x, y);
	}

	public void drawTextCenter(SpriteBatcher batcher, String text, float x,
			float y, float glyphWidth, float glyphHeight) {
		int len = text.length();
		x = x - ((len * glyphWidth) / 2) + glyphWidth / 2;
		drawText(batcher, text, x, y, glyphWidth, glyphHeight);
	}

	public void drawTextCorner(SpriteBatcher batcher, String text, float x,
			float y) {
		x = x + glyphWidth / 2;
		y = y + glyphHeight / 2;
		drawText(batcher, text, x, y);
	}
	
	public void drawTextCorner(SpriteBatcher batcher, String text, float x, float y, float glyphWidth, float glyphHeight) {
		x = x + glyphWidth / 2;
		y = y + glyphHeight / 2;
		drawText(batcher, text, x, y);
	}
}
